define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'products/index' + location.search,
                    add_url: 'products/add',
                    edit_url: 'products/edit',
                    del_url: 'products/del',
                    multi_url: 'products/multi',
                    import_url: 'products/import',
                    table: 'products',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'skulist',
                                    text: __('商品规格'),
                                    title: __('商品规格'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-list',
                                    url: function (row) {
                                        return 'productssku/index?products_id='+row.id
                                    },
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return false;
                                    }
                                },
                            ],
                        },
                        {field: 'id', title: __('Id')},
                        {field: 'goodtype.name', title: __('Goodtype.name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},

                        {field: 'name', title: __('Name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'images', title: __('Images'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images},
                        {field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'price', title: __('Price'), operate:'BETWEEN'},
                        {field: 'del_price', title: __('Del_price'), operate:'BETWEEN'},
                        // {field: 'vip_price', title: __('Vip_price'), operate:'BETWEEN'},
                        {field: 'sellnum', title: __('Sellnum')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'weigh', title: __('Weigh'), operate: false},
                        {field: 'tui_switch', title: __('Tui_switch'), table: table, formatter: Table.api.formatter.toggle},
                        // {field: 'goodtype_id', title: __('Goodtype_id')},

                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'products/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'products/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'products/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            $(document).on("fa.event.appendfieldlist", "#add-form .btn-append", function (e, obj) {
                //绑定动态下拉组件
                Form.events.selectpage(obj);
                //绑定日期组件
                Form.events.datetimepicker(obj);
                //绑定上传组件
                Form.events.faupload(obj);

                //上传成功回调事件，变更按钮的背景
                $(".upload-image", obj).data("upload-success", function (data) {
                    $(this).css("background-image", "url('" + Fast.api.cdnurl(data.url) + "')");
                })
            });
            Controller.api.bindevent();
            Controller.api.sku();
        },
        edit: function () {
            $(document).on("fa.event.appendfieldlist", "#edit-form .btn-append", function (e, obj) {
                //绑定动态下拉组件
                Form.events.selectpage(obj);
                //绑定日期组件
                Form.events.datetimepicker(obj);
                //绑定上传组件
                Form.events.faupload(obj);

                //上传成功回调事件，变更按钮的背景
                $(".upload-image", obj).data("upload-success", function (data) {
                    $(this).css("background-image", "url('" + Fast.api.cdnurl(data.url) + "')");
                })
            });
            Controller.api.bindevent();
            Controller.api.sku();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            sku:function () {
                require(['vue','upload'],function (Vue,Upload) {
                    new Vue({
                        el:"#vuediv",
                        data:{
                            spec_name:'',
                            specList:Config.specList||[],
                            tableData:Config.tableData||[]
                        },
                        mounted(){
                            console.log('Vue创建成功',this.tableData);
                            for (let i = 0; i < this.tableData.length; i++) {
                                this.uploadimg(i);
                            }
                        },
                        watch: {
                            specList: {
                                handler: function (val) {
                                    this.renderTableData(val);
                                },
                                deep: true
                            }
                        },
                        methods:{
                            uploadimg(index){
                                var that = this
                                Upload.api.upload($('#uploadimg'+index), function (e) {
                                    that.tableData[index].image = e.fullurl
                                }, function (e){
                                });
                            },
                            del(index){
                                var that = this
                                Layer.confirm("确认删除？", function(){
                                    that.tableData.splice(index,1);
                                    layer.closeAll();
                                });
                            },
                            addSpec(){
                                if(this.spec_name == ''){
                                    return;
                                }
                                this.specList.push({
                                    name:this.spec_name,
                                    value:[

                                    ]
                                });
                                this.spec_name = '';
                            },
                            removeSpec(index){
                                this.specList.splice(index,1);
                            },
                            addSpecValue(key){
                                this.specList[key].value.push('');
                            },
                            removeSpecValue(key,index){
                                this.specList[key].value.splice(index,1);
                            },
                            renderTableData(list){
                                this.result = [];
                                this.resetSpec(list,0);
                                var newtableData = [];

                                this.result.forEach((item, index) => {
                                    if (this.tableData.length == 0){
                                        newtableData.push({
                                            specificationvalues_names:item,
                                            image:'',
                                            price:'',
                                            del_price:'',
                                            vip_price:'',
                                            stock:''
                                        });
                                    }else{
                                        for (let i = 0; i < this.tableData.length; i++) {
                                            let dataitem = this.tableData[i]
                                            if(item == dataitem.specificationvalues_names){
                                                newtableData.push(dataitem);
                                                break;
                                            }else if (i ==  this.tableData.length -1){
                                                newtableData.push({
                                                    specificationvalues_names:item,
                                                    image:'',
                                                    price:'',
                                                    del_price:'',
                                                    vip_price:'',
                                                    stock:''
                                                });
                                            }
                                        }

                                    }
                                });
                                this.tableData = newtableData;
                                for (let i = 0; i < this.tableData.length; i++) {
                                    this.uploadimg(i);
                                }
                            },
                            //组合规格属性
                            resetSpec(list, index) {
                                if (list[index] != undefined) {
                                    let value = list[index].value;
                                    if (!index) {
                                        this.result = value;
                                    } else {
                                        let res = [];
                                        for (let i of this.result) {
                                            for (let j of value) {
                                                res.push(i + ',' + j);
                                            }
                                        }
                                        if (res.length) {
                                            this.result = res;
                                        }
                                    }
                                    this.resetSpec(list, ++index);
                                }
                            }
                        }
                    });
                });
            }
        }
    };
    return Controller;
});
